package com.store.store.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.sql.SQLIntegrityConstraintViolationException;

/**
 * 全局异常处理器
 */
//表示对添加了这些注解的进行异常拦截
@ControllerAdvice(annotations = {RestController.class, Controller.class})
@Slf4j
@ResponseBody
public class GlobalExceptionHandler {

    /**
     * 表示对这个，sql执行错误，的异常进行拦截
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException sie){
        log.error(sie.getMessage());

        //仅处理主键重复的情况
        if(sie.getMessage().contains("Duplicate entry")){
            String[] split = sie.getMessage().split(" ");
            String msg = split[2] +"已存在";
            return R.error(msg);
        }

        return R.error("插入失败");
    }

    @ExceptionHandler(CustomException.class)
    public R<String> customExceptionHandler(CustomException ex){

        return R.error(ex.getMessage());

    }

}
